//
//  BaseService.m
//  Stock
//
//  Created by blacksun on 11-6-9.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "BaseService.h"


@implementation BaseService
@synthesize workingRequests;
@synthesize delegate;
@synthesize operationQueue;

-(id)initWithDelegate:(id<ServiceDelegate>)aDelegate{
    self = [super init];
    if (self) {
        self.delegate = aDelegate;
        self.workingRequests = [NSMutableArray array];
        self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
        return self;
    }
    return nil;
}

-(void)dealloc{
    [workingRequests makeObjectsPerformSelector:@selector(clearDelegatesAndCancel)];
    self.workingRequests = nil;
    [self.operationQueue cancelAllOperations];
    self.operationQueue = nil;
    [super dealloc];
}

#pragma mark -database operation;
-(void) batchSaveObjects:(NSArray *)models{
    if (!models || [models count]==0) {
        return;
    }
    SQLiteInstanceManager *databaseManager = [SQLiteInstanceManager sharedManager];
    [databaseManager executeUpdateSQL:@"BEGIN TRANSACTION"];
    [models makeObjectsPerformSelector:@selector(save)];
    [databaseManager executeUpdateSQL:@"COMMIT"];
}
-(void) batchAndAsynchronousSaveObjects:(NSArray *)models{
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(batchSaveObjects:) object:models];
    [operationQueue addOperation:operation];
    [operation release];
}
-(NSInteger)countWithTableName:(NSString *)tableName andCriteriaString:(NSString *)criteriaString{
    sqlite3 *database = [[SQLiteInstanceManager sharedManager] database];
	NSInteger count = 0;
	sqlite3_stmt *statement;
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(1) FROM %@ %@",tableName,criteriaString];
	if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, nil ) == SQLITE_OK){
		while (sqlite3_step(statement) == SQLITE_ROW) {
			count = sqlite3_column_int(statement, 0);
		}
		sqlite3_finalize(statement);
		//sqlite3_close(database);
	}else {
		sqlite3_finalize(statement);
		//sqlite3_close(database);
		//NSAssert(0,@"Error select feeds");
		return 0;
	}
	return count;

}

#pragma mark -cancle request
-(void)cancleAllRequest{
    [workingRequests makeObjectsPerformSelector:@selector(clearDelegatesAndCancel)];
    [self.workingRequests removeAllObjects];
}
-(void)cancleRequest:(ASIHTTPRequest *)aRequest{
    [aRequest clearDelegatesAndCancel];
    [self.workingRequests removeObject:aRequest];
}
@end
